package com.sirui.x.learnBoot.global;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sirui.x.learnBoot.util.JacksonUtil;

@ControllerAdvice
public class MvcExceptionHandle {
	
	private static final Logger log = LoggerFactory.getLogger(MvcExceptionHandle.class);

//	javax.validation.ConstraintViolationException
	@ExceptionHandler(value = ServletRequestBindingException.class)
	@ResponseBody
	public MsgDto<?> handleServletRequestBindingException(HttpServletRequest req, HttpServletResponse response,
			ServletRequestBindingException e) {
		log.error("resp: {uri:" + req.getRequestURI() + "}", e);
		return MsgDto.getFail(e.getMessage());
	}

	@ExceptionHandler(value = MsgException.class)
	@ResponseBody
	public MsgDto<?> handleMsgException(HttpServletRequest req, HttpServletResponse response, MsgException e) {
		log.error("resp: {uri:" + req.getRequestURI() + "}", e);
		return MsgDto.getFail(e.getMessage());
	}

	@ExceptionHandler(value = BindException.class)
	@ResponseBody
	public MsgDto<?> bindExceptionHandle(HttpServletRequest req, HttpServletResponse response, BindException e) {

		MsgDto<?> result = wrapperBindingResult(e.getBindingResult());
		log.error("{uri:" + req.getRequestURI() + ", resp: " + JacksonUtil.bean2String(result) + "}", e);
		return result;
	}

	@ExceptionHandler(value = MethodArgumentNotValidException.class)
	@ResponseBody
	public MsgDto<?> handleMethodArgumentNotValidException(HttpServletRequest req, HttpServletResponse response,
			MethodArgumentNotValidException e) {
		log.error("resp: {uri:" + req.getRequestURI() + "}", e);
		return wrapperBindingResult(e.getBindingResult());
	}

	@ExceptionHandler(value = Throwable.class)
	@ResponseBody
	public MsgDto<?> exceptionHandle(HttpServletRequest req, HttpServletResponse response, Throwable e) {
		log.error("resp: {uri:" + req.getRequestURI() + "}", e);
		return MsgDto.getFail("系统繁忙，请稍后再试");
	}

	private MsgDto<?> wrapperBindingResult(BindingResult result) {
		if ((result != null) && !result.getAllErrors().isEmpty()) {
			return MsgDto.getFail(result.getAllErrors().get(0).getDefaultMessage());
		}
		return MsgDto.getFail("系统繁忙，请稍后再试");
	}
}
